import store from '@/store';
import { getToken_AUTH } from '@/utils/auth.js';
import { configs } from '@/assets/config/config.js';
const BASE_API = configs.BASE_URL ? configs.BASE_URL : '';
var _count = 0;
var _401_count = 0;

const service = function(config, custom_config) {
	let resultConfig = initConfig(config, custom_config)
	return requestMethod(resultConfig)
}

function initConfig(config, custom_config) {
	let options = {
		url: handleUrl(config.url),
		data: config.data,
		method: config.method ? config.method.toUpperCase() : 'GET',
		header: handleToken(config.header || {}),
		dataType: config.dataType || 'json',
		responseType: config.responseType || 'text',
		custom_config: custom_config || {}
	}
	return options
}

// uni.request
function requestMethod(httpConfig) {
	let _options = {
		loading_flag: false,
		loading_text: '请求中...', // 最好不要超过8个字符
		loading_mask: true, // 平台差异5+App、微信小程序、百度小程序
		loading_hide: true, // 因为uni.showLoading是单例对象,所以多个蒙层的时候,调用uni.hideLoading()会全部关闭,为此多定义一个参数支持是否要手动调用uni.hideLoading()来结束uni.showLoading
		show_error: true, // 是否显示接口为200但code非0的错误提示
		data_format: true, // 默认去掉一层data数据层
	}
	_options = Object.assign(_options, httpConfig.custom_config);
	if (_options.loading_flag) {
		_count++;
		if(_count === 1) {
			uni.showLoading({
				title: _options.loading_text,
				mask: _options.loading_mask,
				fail: () => {
					console.error(`该接口（${httpConfig.url}）的蒙层打开失败`)
				}
			})
		}
	}
	// 发出请求
	const httpPromise = new Promise((resolve, reject) => {
		let requestParames = Object.assign(httpConfig, {
			success: (res) => {
				if (_options.loading_hide) {
					closeLoading(_options);
				}
				if(res.statusCode === 401) {
					store.commit('SET_TOKEN');
					store.commit('SET_USERNAME');
					if(_401_count === 0) {
						_401_count++;
						uni.showModal({
							title: '温馨提示',
							content: '登录已经过期',
							showCancel: false,
							success: (res) => {
								if (res.confirm) {
									uni.showLoading({
										title: '重新登录中...'
									})
									store.dispatch('Login').then(res => {
										let pages = getCurrentPages();
										let curPage = pages[pages.length - 1];
										curPage.onLoad();
										uni.hideLoading();
									})
								}
							},
							complete: () => {
								_401_count--;
							}
						});
					}
					reject('登录过期');
					return;
				}
				if (_options.show_error) {
					if (res.data.headers.code !== 200 && res.data.headers.code !== 0) {
						uni.showModal({
							title: '温馨提示',
							content: res.data.headers.message,
							showCancel: false
						});
						reject('code不是0');
						return;
					}
				}
				if(res.statusCode === 200) {
					_options.data_format ? resolve(res.data.data) : resolve(res);
				}else {
					reject(res);
				}
			},
			fail: (err) => {
				if (_options.loading_hide) {
					closeLoading(_options);
				}
				uni.showModal({
					title: '网络异常',
					content: '请检查网络是否正常或者关闭结束应用重新打开',
					showCancel: false
				});
				reject(err);
			},
		});
		uni.request(requestParames);
	})
	return httpPromise;
}

// uni.uploadFile
export function uploadFile(config) {
  const fileType = {};
  if (config.file) {
    fileType.file = config.file;
  }else {
    fileType.filePath = config.tempFilePaths;
  }
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: handleUrl(config.url),
      ...fileType,
			name: 'file',
			header: {
				'Authorization': getToken_AUTH(),
			},
			formData: config.data || {},
      timeout: 1000 * 20,
			success: res => {
        if(res.statusCode === 200) {
          const result = JSON.parse(res.data);
          if (result.headers.code === 0) {
				    resolve(result.data);
          }
        }
			},
			fail: err => {
				reject(err);
				uni.showModal({
					title: '上传失败',
					content: err,
					showCancel: false
				});
			}
		})
	});
}


// 工具方法
function closeLoading(_options) {
	if(_options.loading_flag && _count > 0) {
		_count--;
	}
  if(_count === 0) {
    uni.hideLoading();
  }
}

function handleToken(headers) {
	headers['Authorization'] = getToken_AUTH() || '';
	return headers;
}

function handleUrl(url) {
	let URL = '';
	if (url.indexOf('http') !== -1 || url.indexOf('https') !== -1) {
		URL = url;
	}else {
		if(!BASE_API) {
			console.warn(`温馨提示：当前这个（${url}）路径识别为内部路径，但是基础域名为空，请检查程序是否异常。`)
		}
		if (url.charAt(0) !== '/' && BASE_API.charAt(BASE_API.length - 1) !== '/') {
			url = '/' + url;
		}
		if (url.charAt(0) === '/' && BASE_API.charAt(BASE_API.length - 1) === '/') {
			url = url.substr(1);
		}
		URL = BASE_API + url;
	}
	return URL
}

export default service;
